﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using Volo.Abp.AutoMapper;
using Xms.Abp.BackgroundJob;

namespace BackgroundJobManagement;

public class BackgroundJobManagementDomainAutoMapperProfile : Profile
{
    public BackgroundJobManagementDomainAutoMapperProfile()
    {
        CreateMap<BackgroundJobInfo, BackgroundJobEntity>()
            .ConstructUsing(x => new BackgroundJobEntity(x.Id))
            .Ignore(record => record.ReferenceJobs)
            .Ignore(record => record.RetryIntervals)
            .Ignore(record => record.ConcurrencyStamp)
            .Ignore(record => record.ExtraProperties)
            .AfterMap((a, b) =>
            {
                b.ReferenceJobs = a.ReferenceJobs?.Select(s => s.ToString())?.JoinAsString(",");
                b.RetryIntervals = a.RetryIntervals?.Select(s => s.ToString())?.JoinAsString(",");
            });

        CreateMap<BackgroundJobEntity, BackgroundJobInfo>()
            .Ignore(record => record.ReferenceJobs)
            .Ignore(record => record.RetryIntervals)
            .AfterMap((a, b) =>
            {
                var rjs = a.ReferenceJobs?.Split(',')?.Select(s => Guid.Parse(s))?.ToList();
                if (rjs != null && rjs.Any())
                {
                    b.ReferenceJobs.AddRange(rjs);
                }
                var ris = a.RetryIntervals?.Split(',')?.Select(s => int.Parse(s))?.ToList();
                if (rjs != null && rjs.Any())
                {
                    b.RetryIntervals.AddRange(ris);
                }
            });

        CreateMap<BackgroundScheduleInfo, BackgroundScheduleEntity>()
            .Ignore(record => record.ConcurrencyStamp)
            .Ignore(record => record.ExtraProperties);

        CreateMap<BackgroundScheduleEntity, BackgroundScheduleInfo>();
    }
}
